<template>
  <div>
    <img class="w-full h-full" v-if="!isLoading && !error" :src="imageSrc" :alt="alt" />
    <div v-if="isLoading">Loading...</div>
    <div v-if="error">Failed to load image</div>
  </div>
</template>

<script lang="ts" setup>
import { ref, onMounted } from 'vue';
import { useUserStoreWithOut } from '@/store/modules/user';

const props = defineProps({
  src: {
    type: String,
    required: true
  },
  alt: {
    type: String,
    default: ''
  }
});
const imageSrc = ref('');
const isLoading = ref(true);
const error = ref(false);
const userStore = useUserStoreWithOut();
const accessToken = userStore.getToken;

onMounted(() => {
  const headers = {
    token: accessToken
  };

  fetch(props.src, { headers })
    .then((response) => {
      if (response.ok) {
        console.log('imgResponse', response);
        return response.blob();
      } else {
        throw new Error('Failed to fetch image');
      }
    })
    .then((blob) => URL.createObjectURL(blob))
    .then((url) => {
      imageSrc.value = url;
      isLoading.value = false;
    })
    .catch((error) => {
      console.error('imgError', error);
      isLoading.value = false;
      error.value = true;
    });
});
</script>
